<?php 
include "UploadImageClass.php";
class webList{

	/**
	 * 数据库连接
	 * @var [type]
	 */
	private $_db;

	private $statusCode = array(
		200 => "OK",
		204 => "Not Content",
		400 => "Bad Request",
		403 => "Forbidden",
		404 => "Not Found",
		405 => "Method is Not Allow",
		500 => "Server Internal Error"

		);

	/**
	 * 实例化数据库连接
	 */
	public function __construct($db)
	{
		$this->_db = $db;
	}


	/**
	 * API启动方法
	 * @return [type] [description]
	 */
	public function run()
	{	

		$path = isset($_SERVER["PATH_INFO"])?explode("/", $_SERVER["PATH_INFO"]):explode("/", $_SERVER["QUERY_STRING"]);
		try{
					switch ($path[2]) {
						case 'add':
							
							$this->input();
							break;

						case 'list':
							$this->webList();
							break;

						case 'mylist':
							$this->myWebList();
							break;

						case 'del':
							$this->delete();
							break;

						case 'img':
							$this->upImg();
							break;
						
						default:
							echo json_encode("参数不合法",400);
							break;
					}

		} catch (Exception $e) {
			$this->_json($e->getMessage(),$e->getCode());
		}

	}

	/**
	 * 查看所有站点
	 * @return [type] [description]
	 */
	public function webList()
	{
		$sql = "select group.id as gid,group.group_name,web.* from `group`,web where group.id = web.group_id and web.web_status = 0";
		$smt = $this->_db->prepare($sql);
		$smt->execute();
		$row = $smt->fetchAll(PDO::FETCH_ASSOC);

		$arr = [];
		foreach ($row as $value) {
			if($value['gid'] == $value['group_id']){
				$arr[$value["group_name"]][] = $value;
			}
		} 

		echo json_encode($arr);
		exit;
	}

	/**
	 * 删除站点
	 * @return [type] [description]
	 */
	public function delete()
	{

		$token   = isset($_POST['token'])?$_POST['token']:'';
		$user_id = isset($_POST['user_id'])?$_POST['user_id']:'';
		$web_id = isset($_POST['web_id'])?$_POST['web_id']:'';
		$sessionId = session_id();

		if($token != $sessionId){
			throw new Exception("请先登录", 400);
		}

		if(empty($user_id)){
			throw new Exception("用户id不能为空", 400);
		}

		if(empty($web_id)){
			throw new Exception("站点id不能为空", 400);
		}		

		$sqlWeb = "select * from web where id = ? and user_id = ?";
		$smtWeb = $this->_db->prepare($sqlWeb);
		$smtWeb->bindParam(1,$web_id);
		$smtWeb->bindParam(2,$user_id);
		$smtWeb->execute();
		$rowWeb = $smtWeb->fetch(PDO::FETCH_ASSOC);

		$sqlUser = "select * from user where id = ? and status =1";
		$smtUser = $this->_db->prepare($sqlUser);
		$smtUser->bindParam(1,$user_id);
		$smtUser->execute();
		$rowUser = $smtUser->fetch(PDO::FETCH_ASSOC);

		
		        
		if(!is_array($rowWeb) && !is_array($rowUser)){
			throw new Exception("您无权删除此站点", 400);
		}

		$sql = "delete from web where id = ?";
		$smt = $this->_db->prepare($sql);
		$smt->bindParam(1,$web_id);
		$web_name = $rowWeb['web_name'];

		system("sudo /root/del.sh {$web_name}",$re);

       
		if($smt->execute() && $re===0){
			$this->_json("删除成功",200);
		}else{
			throw new Exception("删除失败", 400);
		}

		
	}


	/**
	 * 用户站点
	 * @param  int $user_id 用户id* 
	 * @param  string $token token
	 * @return [type]          [description]
	 */
	public function myWebList()
	{	

		$token   = isset($_POST['token'])?$_POST['token']:'';
		$user_id = isset($_POST['user_id'])?$_POST['user_id']:'';
		$sessionId = session_id();

		if($token != $sessionId){
			throw new Exception("请先登录", 400);
		}

		if(empty($user_id)){
			throw new Exception("用户id不能为空", 400);
		}

		

		$sql = "select * from web where user_id = ?";
		$smt = $this->_db->prepare($sql);
		$smt->bindParam(1,$user_id);
		$smt->execute();
		$row = $smt->fetchAll(PDO::FETCH_ASSOC);

		echo json_encode(["data"=>$row,"code"=>200]);
		exit;
	}

	/**
	 * 创建站点
	 * @param  string $web_name   站点名称
	 * @param  string $web_info   站点信息
	 * @param  string $web_image  站点图片
	 * @param  string $web_author 站点作者
	 * @param  int    $web_status 站点状态（公开或私有）
	 * @param  int    $user_id    用户id
	 * @param  string $group_id 站点所在组
	 * @return [type]             [description]
	 */
	public function input()
	{

		$web_name = isset($_POST["web_name"])?$_POST["web_name"]:'';
		$web_info = isset($_POST["web_info"])?$_POST["web_info"]:'';
		$web_author = isset($_POST["web_author"])?$_POST["web_author"]:'';
		(int)$web_status = isset($_POST["web_status"])?$_POST["web_status"]:'';
		$user_id    = isset($_POST["user_id"])?$_POST["user_id"]:'';
		$group_id = isset($_POST["group_id"])?$_POST["group_id"]:'';

		$sqlName = "select * from web where web_name = ?";
		$smt = $this->_db->prepare($sqlName);
		$smt->bindParam(1,$web_name);
		$smt->execute();
		$row = $smt->fetch(PDO::FETCH_ASSOC);
		



		// echo'<pre>'; 
		// print_r($web_status); 
		// echo'</pre>'; 
		// exit;
		        
		if(is_array($row)){
			throw new Exception("该站点已存在", 400);
		}

		if(empty($web_name)){
			throw new Exception("站点名称不能为空", 400);
		}

		if(empty($web_info)){
			throw new Exception("站点简介不能为空", 400);
		}

		if(empty($web_author)){
			throw new Exception("站点作者不能为空", 400);
		}

		if($web_status !=0 && $web_status!=1){
			throw new Exception("站点状态不能为空", 400);
		}

		if(empty($user_id)){
			throw new Exception("用户id不能为空", 400);
		}

		if(empty($group_id)){
			throw new Exception("分组id不能为空", 400);
		}

		$create_time = date('Y-m-d H:i:s',time());
		$sql = "insert into web(web_name,web_info,web_image,web_author,web_status,user_id,group_id,create_time) values(?,?,?,?,?,?,?,?)";
		$smt = $this->_db->prepare($sql);
		$smt->bindParam(1,$web_name);
		$smt->bindParam(2,$web_info);
		$smt->bindParam(3,$web_image);
		$smt->bindParam(4,$web_author);
		$smt->bindParam(5,$web_status);
		$smt->bindParam(6,$user_id);
		$smt->bindParam(7,$group_id);
		$smt->bindParam(8,$create_time);

		
		if(!$smt->execute()){
			throw new Exception("站点提交失败", 500);
		}

		$sqlUser = "select password from user where user.id = ?";
		$smt = $this->_db->prepare($sqlUser);
		$smt->bindParam(1,$user_id);
		$smt->execute();
		$row = $smt->fetch(PDO::FETCH_ASSOC);

		$this->createSvn($web_name, $web_name, $row["password"]);

		$this->createFtp($web_name, $web_name, $row["password"]);


		

		$data = array(
			'web_name' => $web_name,
			'web_info' => $web_info,
			'web_author' => $web_author,
			'web_id' => $this->_db->lastInsertId(),
			'web_status' => $web_status,
			'user_id'    => $user_id,
			'group_id'  => $group_id,
			'create_time' => $create_time

			);

		echo json_encode(["data"=>$data,"code"=>200]);
		exit;
	}

	/**
	 * 图片上传
	 * @param int $web_id 站点id
	 * @return [type] [description]
	 */
	private function upImg(){

		$web_id = isset($_POST["web_id"])?$_POST["web_id"]:'';

		if(empty($web_id)){
			throw new Exception("站点id不能为空", 400);
		}

		$file = new UploadImage();	
		if(isset($_FILES['file']) && $_FILES['file']['error']===0){
			$data=$file->up($_FILES['file'],"image");
			$web_image = $data['filename']; 
		}


		if(isset($_FILES['file']) && $_FILES['file1']['error']===0){
			$data1=$file->up($_FILES['file1'],"image");
			$web_image1 = $data['filename']; 
		}


		if(isset($_FILES['file']) && $_FILES['file2']['error']===0){
			$data2=$file->up($_FILES['file2'],"image");
			$web_image2 = $data['filename']; 
		}

		$sql = "update web set web_image = ?, web_image1 = ?, web_image2 = ? where id = ?";
		$smt = $this->_db->prepare($sql);
		$smt->bindParam(1,$web_image);
		$smt->bindParam(2,$web_image1);
		$smt->bindParam(3,$web_image2);
		$smt->bindParam(4,$web_id);

		if($smt->execute()){
			echo json_encode(["message"=>"上传成功","data"=>["web_image"=>$web_image,"web_image1"=>$web_image1,"web_image2"=>$web_image2],"code"=>200]);
			exit;
		}
	}

	/**
	 * svn站点创建
	 * @return [type] [description]
	 */
	private function createSvn($web_name, $web_name, $password)
	{	
		        
		system("sudo /root/svn.sh {$web_name} {$web_name} {$password}",$rs);

		if($rs !== 0){
			throw new Exception("SVN站点创建失败", 500);
		}
	}

	/**
	 * ftp站点创建
	 * @param  [type] $web_name [description]
	 * @param  [type] $email    [description]
	 * @param  [type] $password [description]
	 * @return [type]           [description]
	 */
	private function createFtp($web_name, $web_name, $password)
	{       
		system("sudo /root/ftp.sh {$web_name} {$web_name} {$password}", $rs);
		if($rs !== 0){
			throw new Exception("FTP站点创建失败", 500);
		}
	}


	/**
	 * 数据输出
	 * @param  string $message 提示信息
	 * @param  int $code       提示状态码
	 * @return array           返回信息
	 */
	private function _json($message, $code)
	{	
		if($code!=200 && $code>200){
			header("HTTP/1.1 ".$code.' '.$this->statusCode[$code]);
		}

		header("Content-Type:application/json;charset=utf-8");

		if(!empty($message)){
			echo json_encode(array("message"=>$message, "code"=>$code));
			exit;
		}
	}
}






 ?>